package io.renren.modules.sp.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sp.dto.SpBaseMatchItemDTO;
import io.renren.modules.sp.dto.SpMatchItemDTO;
import io.renren.modules.sp.entity.SpBaseMatchItemEntity;
import io.renren.modules.sp.entity.SpMatchEntity;
import io.renren.modules.sp.entity.SpMatchItemEntity;
import io.renren.modules.sp.excel.SpMatchItemCountExcel;
import io.renren.modules.sp.excel.SpMatchItemEntryCountExcel;
import io.renren.modules.sp.excel.SpMatchItemExcel;
import io.renren.modules.sp.service.MainIndividualService;
import io.renren.modules.sp.service.SpBaseMatchItemService;
import io.renren.modules.sp.service.SpMatchItemService;
import io.renren.modules.sp.service.SpMatchService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
* 赛项
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-20
*/
@RestController
@RequestMapping("sp/spmatchitem")
@Api(tags="赛项")
public class SpMatchItemController extends BaseController{
    @Autowired
    private SpMatchItemService spMatchItemService;
    @Autowired
    private SpBaseMatchItemService spBaseMatchItemService;
    @Autowired
    private SpMatchService spMatchService;
    @Autowired
    private SysUserService sysUserService;


    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    //@RequiresPermissions("sp:spmatchitem:page")
    public Result<PageData<SpMatchItemDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        if(this.authFlag()) {
            //如果当前用户是赛项管理员，则可以查看当前赛事下的所有赛项
            SpMatchEntity entity = spMatchService.selectById((String)params.get("matchId"));
            if(entity!=null && entity.getAdminId() == user.getId().intValue()){
                //当前用户是赛项管理员，可以不加过滤条件
            }else{
                params.put("adminId", user.getId());
            }
        }

        // 打分员
        String userType = sysUserService.getSysUserType();
        if ("5".equals(userType)) {
            if(user.getMatchItemId()!=null && user.getMatchItemId() != 0) {
                params.put("id", user.getMatchItemId());
            }
        }


        PageData<SpMatchItemDTO> page = spMatchItemService.page(params);
        // 循环page
        List<SpMatchItemDTO> list = page.getList();
        for (SpMatchItemDTO spMatchItemDTO : list) {
            // 赛事名称
            SpMatchEntity spMatchEntity = spMatchService.selectById(spMatchItemDTO.getMatchId());
            if(spMatchEntity!=null){
                spMatchItemDTO.setMatchName(spMatchEntity.getMatchName());
            }
            // 赛项名称
            SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemService.selectById(spMatchItemDTO.getBaseMatchItemId());
            if(spBaseMatchItemEntity!=null){
                spMatchItemDTO.setBaseMatchItemName(spBaseMatchItemEntity.getItemName());
                spMatchItemDTO.setItemType(spBaseMatchItemEntity.getItemType());
                spMatchItemDTO.setIsDraw(spBaseMatchItemEntity.getIsDraw());
            }
            String type = (String)params.get("type");
            Map<String,Object> total = spMatchItemService.itemTotal(spMatchItemDTO.getId(), type);
            spMatchItemDTO.setTotal(total);
        }
        return new Result<PageData<SpMatchItemDTO>>().ok(page);
    }

    /**
     * 下载参赛照片
     */
    @LogOperation("下载参赛照片")
    @GetMapping("/downloadHeaderFile")
    public Result<String> downloadHeaderFile(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        return spMatchItemService.downloadHeaderFile(params,response);
    }

    @GetMapping("list")
    public Result<List<SpMatchItemDTO>> list(@ApiIgnore @RequestParam Map<String, Object> params){
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        if(this.authFlag()) {
            //如果当前用户是赛项管理员，则可以查看当前赛事下的所有赛项
            SpMatchEntity entity = spMatchService.selectById((String)params.get("matchId"));
            if(entity!=null && entity.getAdminId() == user.getId().intValue()){
                //当前用户是赛项管理员，可以不加过滤条件
            }else{
                params.put("adminId", user.getId());
            }
        }
        List<SpMatchItemDTO> list = spMatchItemService.list(params);
        for (SpMatchItemDTO spMatchItemDTO : list) {
            // 赛事名称
            SpMatchEntity spMatchEntity = spMatchService.selectById(spMatchItemDTO.getMatchId());
            if(spMatchEntity!=null){
                spMatchItemDTO.setMatchName(spMatchEntity.getMatchName());
            }
            // 赛项名称
            SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemService.selectById(spMatchItemDTO.getBaseMatchItemId());
            if(spBaseMatchItemEntity!=null){
                spMatchItemDTO.setBaseMatchItemName(spBaseMatchItemEntity.getItemName());
                spMatchItemDTO.setItemType(spBaseMatchItemEntity.getItemType());
                spMatchItemDTO.setIsDraw(spBaseMatchItemEntity.getIsDraw());
            }
        }
        return new Result<List<SpMatchItemDTO>>().ok(list);
    }


    @GetMapping("{id}")
    @ApiOperation("信息")
    //@RequiresPermissions("sp:spmatchitem:info")
    public Result<SpMatchItemDTO> get(@PathVariable("id") Long id){
        SpMatchItemDTO data = spMatchItemService.get(id);
        if(data.getAdminId()!=null){
            SysUserEntity sysUserEntity = sysUserService.selectById(data.getAdminId());
            if(sysUserEntity!=null){
                data.setAdminName(sysUserEntity.getRealName());
            }
        }
        return new Result<SpMatchItemDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    //@RequiresPermissions("sp:spmatchitem:save")
    public Result save(@RequestBody SpMatchItemDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        spMatchItemService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    //@RequiresPermissions("sp:spmatchitem:update")
    public Result update(@RequestBody SpMatchItemDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        spMatchItemService.updateMatchItem(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    //@RequiresPermissions("sp:spmatchitem:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        return spMatchItemService.deleteItem(ids);
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    //@RequiresPermissions("sp:spmatchitem:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        //List<SpMatchItemDTO> list = spMatchItemService.list(params);
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        if(this.authFlag()) {
            //如果当前用户是赛项管理员，则可以查看当前赛事下的所有赛项
            SpMatchEntity entity = spMatchService.selectById((String)params.get("matchId"));
            if(entity!=null && entity.getAdminId() == user.getId().intValue()){
                //当前用户是赛项管理员，可以不加过滤条件
            }else{
                params.put("adminId", user.getId());
            }
        }
        params.put("limit", "20000");
        PageData<SpMatchItemDTO> page = spMatchItemService.page(params);

        // 赛事名称
        SpMatchEntity spMatchEntity = new SpMatchEntity();
        if(page.getList().size()>0){
            spMatchEntity = spMatchService.selectById(page.getList().get(0).getMatchId());
        }

        // 循环page
        List<SpMatchItemDTO> list = page.getList();
        for (SpMatchItemDTO spMatchItemDTO : list) {
            if(spMatchEntity!=null){
                spMatchItemDTO.setMatchName(spMatchEntity.getMatchName());
            }
            // 赛项名称
            SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemService.selectById(spMatchItemDTO.getBaseMatchItemId());
            if(spBaseMatchItemEntity!=null){
                spMatchItemDTO.setBaseMatchItemName(spBaseMatchItemEntity.getItemName());
            }
            String type = (String)params.get("type");
            Map<String,Object> total = spMatchItemService.itemTotal(spMatchItemDTO.getId(), type);
            //spMatchItemDTO.setTotal(total);
            spMatchItemDTO.setNopassNumCount((Long)total.get("nopassNum"));
            spMatchItemDTO.setGroupsNumCount((Long)total.get("groupsNum"));
            spMatchItemDTO.setStudentNumCount((Long)total.get("studentNum"));
            spMatchItemDTO.setTeacherNumCount((Long)total.get("teacherNum"));
            spMatchItemDTO.setTeamsNumCount((Long)total.get("teamsNum"));
        }

        ExcelUtils.exportExcelToTarget(response, spMatchEntity.getMatchName()+ DateUtils.format(new Date()), spMatchEntity.getMatchName(), list, SpMatchItemCountExcel.class);
    }


    @GetMapping("exportCount")
    @ApiOperation("导出")
    @LogOperation("导出")
    //@RequiresPermissions("sp:spmatchitem:export")
    public void exportCount(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        String matchId = (String) params.get("matchId");
        //如果当前用户是赛项管理员，则可以查看当前赛事下的所有赛项
        SpMatchEntity entity = spMatchService.selectById(matchId);
        if(this.authFlag()) {
            if (entity != null && entity.getAdminId() == user.getId().intValue()) {
                //当前用户是赛项管理员，可以不加过滤条件
            } else {
                params.put("adminId", user.getId());
            }
        }
        params.put("limit", "20000");
        PageData<SpMatchItemDTO> page = spMatchItemService.page(params);

        // 循环page
        List<SpMatchItemDTO> list = page.getList();
        List<SpMatchItemEntryCountExcel> countExcelList = new ArrayList<>();
        SpMatchItemEntryCountExcel excel = null;
        for (int i = 0; i < list.size(); i++) {
            SpMatchItemDTO spMatchItemDTO = list.get(i);
            excel = new SpMatchItemEntryCountExcel();
            // 赛项名称
            SpBaseMatchItemEntity spBaseMatchItemEntity = spBaseMatchItemService.selectById(spMatchItemDTO.getBaseMatchItemId());
            if (spBaseMatchItemEntity != null) {
                excel.setBaseMatchItemName(spBaseMatchItemEntity.getItemName());
            }
            String type = (String) params.get("type");
            Map<String, Object> total = spMatchItemService.itemEntryTotal(Long.parseLong(matchId), spMatchItemDTO.getId(), type);
            if (total != null) {
                //long studentNum = (Long) total.get("studentNum");
                excel.setId(Long.valueOf(i + 1));
                excel.setMatchName(entity.getMatchName());
                excel.setStudentNum((Long) total.get("studentNum"));
                excel.setGroupsNum((Long) total.get("groupsNum"));
                excel.setPassNum((Long) total.get("passNum"));
                excel.setPassGroupNum((Long) total.get("passGroupNum"));
                excel.setXGroupNum((Long) total.get("xGroupNum"));
                excel.setXNum((Long) total.get("xNum"));
                excel.setCGroupNum((Long) total.get("cGroupNum"));
                excel.setCNum((Long) total.get("cNum"));
                excel.setGGroupNum((Long) total.get("gGroupNum"));
                excel.setGNum((Long) total.get("gNum"));
            }else{
                excel.setId(Long.valueOf(i + 1));
                excel.setMatchName(entity.getMatchName());
                excel.setStudentNum(0L);
                excel.setGroupsNum(0L);
                excel.setPassNum(0L);
                excel.setPassGroupNum(0L);
                excel.setXGroupNum(0L);
                excel.setXNum(0L);
                excel.setCGroupNum(0L);
                excel.setCNum(0L);
                excel.setGGroupNum(0L);
                excel.setGNum(0L);
            }
            countExcelList.add(excel);
        }
        String fileName = entity.getMatchName() + "-" + DateUtils.format(new Date()) + "-报名情况概览";
        ExcelUtils.exportExcelToTarget(response, fileName, "", countExcelList, SpMatchItemEntryCountExcel.class);
    }

    @PostMapping("queryBaseMatchItem")
    public Result<SpBaseMatchItemEntity> get(@RequestBody SpMatchItemDTO dto) {
        SpMatchItemEntity data = spMatchItemService.selectById(dto.getId());
        if (data != null) {
            SpBaseMatchItemEntity baseMatchItemEntity = spBaseMatchItemService.selectById(data.getBaseMatchItemId());
            return new Result<SpBaseMatchItemEntity>().ok(baseMatchItemEntity);
        }
        return new Result<SpBaseMatchItemEntity>();
    }

    //queryBymatchItemId
    @PostMapping("queryBymatchItemId")
    public Result<Map<String,Object>> queryBymatchItemId(@RequestBody SpMatchItemDTO dto) {
        Map<String, Object> data = spMatchItemService.queryBymatchItemId(dto.getId());
        if (data != null) {
            return new Result<Map<String, Object>>().ok(data);
        }
        return new Result<Map<String, Object>>();
    }

    //queryBymatchItemId
    @PostMapping("updateNotice")
    public Result<Map<String,Object>> updateNotice(@RequestBody SpMatchItemDTO dto) {
       spMatchItemService.updateNotice(dto);
        return new Result<Map<String, Object>>();
    }

    /**
     * 开放抽签
     * @param dto
     * @return
     */
    @PostMapping("openDraw")
    @LogOperation("开放抽签")
    public Result<Map<String,Object>> openDraw(@RequestBody SpMatchItemDTO dto) {
        SpMatchItemEntity spMatchItemEntity = spMatchItemService.selectById(dto.getId());
        if(spMatchItemEntity!=null){
            spMatchItemEntity.setDrawOpen(1);
        }
        spMatchItemService.updateById(spMatchItemEntity);
        spMatchItemService.openDraw(dto.getId());
        return new Result<Map<String, Object>>();
    }

    //同步数据
    @PostMapping("syncData")
    @LogOperation("同步数据")
    public Result<Map<String,Object>> syncData(@RequestBody SpMatchItemDTO dto) {
        spMatchItemService.syncData();
        return new Result<Map<String, Object>>();
    }

    //显示、隐藏成绩
    @PostMapping("scoreOpen")
    @LogOperation("显示、隐藏成绩")
    public Result<Map<String,Object>> scoreOpen(@RequestBody SpMatchItemDTO dto) {
        spMatchItemService.scoreOpen(dto.getId());
        return new Result<Map<String, Object>>();
    }



}
